package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.CsSystemSourcePreSetInfo;
import org.nmgyjt.springboot.beans.admin.StatisticBean;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.CsSystemSourcePreSetInfoResponse;
import org.nmgyjt.springboot.entity.admin.CsSystemSourceType;
import org.nmgyjt.springboot.entity.refuge.RefugeInfo;
import org.nmgyjt.springboot.mapper.CsSystemAdminMapper;
import org.nmgyjt.springboot.mapper.RefugeMapper;
import org.nmgyjt.springboot.service.ICsSystemSourcePreSetInfoService;
import org.nmgyjt.springboot.service.ICsSystemSourceTypeService;
import org.nmgyjt.springboot.service.RefugeService;
import org.nmgyjt.springboot.utils.ZWWXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Service
public class RefugeServiceImpl extends ServiceImpl<RefugeMapper, RefugeInfo> implements RefugeService {
    @Autowired
    private RefugeMapper refugeMapper;
    @Autowired
    CsSystemAdminMapper csSystemAdminMapper;
    @Autowired
    ZWWXUtils zwwxUtils;
    @Autowired
    private ICsSystemSourcePreSetInfoService iCsSystemSourcePreSetInfoService;
    @Autowired
    ICsSystemSourceTypeService sourceTypeService;


    @Override
    public RefugeInfo getByDepId(String depId) {
        QueryWrapper<RefugeInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        RefugeInfo refugeInfo = null;
        try {
            refugeInfo = refugeMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(refugeInfo)) {
                return refugeInfo;
            }
//            else{
//                RefugeInfo refugeInfo1=new RefugeInfo();
//                CsSystemIDSelectBean csSystemIDSelectBean=new CsSystemIDSelectBean();
//                csSystemIDSelectBean.setId(depId);
//                CsSystemDeptResponse detailCsSystemOrg=iCsSystemDeptService.detailCsSystemOrg(csSystemIDSelectBean);
//                if(!ObjectUtils.isEmpty(detailCsSystemOrg)){
//                    refugeInfo1.setRefugeName(detailCsSystemOrg.getName());
//                    refugeInfo1.setRefugeType(detailCsSystemOrg.getSourceType());
//                }
//                return refugeInfo1;
//            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return refugeInfo;
    }

    @Override
    public Map<String, Object> getrefugeStatistics(StatisticBean statisticBean) {
        Map<String, Object> retMap = new LinkedHashMap<>();
        QueryWrapper<CsSystemAdmin> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            queryWrapper.eq("phone", statisticBean.getCreatedBy());
            queryWrapper.eq("superior_org", statisticBean.getSuperOrgId());
        }else{
            queryWrapper.eq("org_id", statisticBean.getSuperOrgId());
        }
        queryWrapper.orderByDesc("id").last("limit 1");
        CsSystemAdmin csSystemAdmin = csSystemAdminMapper.selectOne(queryWrapper);
        String sql = " AND r.state <> '1'";
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            sql = sql + " AND a.superior_org='" + csSystemAdmin.getOrgId() + "'";
        } else {
            sql = sql + " AND a.superior_org='-1'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getName())) {
            sql = sql + " AND a.org_name like '%" + statisticBean.getName() + "%'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getType())) {
            sql = sql + " AND ext.source_type='" + statisticBean.getType() + "'";
        }
        String sql2 = "";
        if (StringUtils.isNotEmpty(statisticBean.getStatus())) {
            if ("1".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '0' ";
            }
            if ("2".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '2' ";
            }

        }
        List<Map<String, Object>> List = refugeMapper.statisticRefug(sql, sql2);
//        List<Map<String, Object>> countTypeList = refugeMapper.statisticRefugTypeCountStatus(csSystemAdmin.getOrgId());
        Integer refugeCount = null == csSystemAdmin ? 0 : refugeMapper.statisticRefugCount(csSystemAdmin.getOrgId());
        Integer refugeTypeCount = null == csSystemAdmin ? 0 : refugeMapper.statisticRefugTypeCount(csSystemAdmin.getOrgId());

        List<Map<String, Object>> countTypeList = new ArrayList<>();
        queryWrapper.clear();
        if (null == csSystemAdmin) {
            queryWrapper.eq("superior_org", statisticBean.getSuperOrgId());
        } else {
            queryWrapper.eq("org_id", csSystemAdmin.getSuperiorOrg());
        }

        queryWrapper.eq("menu_id", statisticBean.getMenuId());
        CsSystemAdmin bean = csSystemAdminMapper.selectOne(queryWrapper);
        CsSystemSourcePreSetInfo preSetInfo = null;
        if (null == bean) {
            preSetInfo = iCsSystemSourcePreSetInfoService.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, statisticBean.getSuperOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, "1000000014").orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
        } else {
            preSetInfo = iCsSystemSourcePreSetInfoService.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, bean.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, "1000000014").orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
        }

        CsSystemSourcePreSetInfoResponse infoResponse = new CsSystemSourcePreSetInfoResponse();
        List<CsSystemSourceType> sourceTypes1 = new ArrayList<>();
        infoResponse.setMenuId(bean == null ? "1000000014" : bean.getMenuId());
        infoResponse.setOrgId(bean == null ? statisticBean.getSuperOrgId() : bean.getOrgId());
        if (null != preSetInfo) {
            List<String> preSetData = JSONObject.parseObject(preSetInfo.getPreSetTypes(), List.class);
            if (!CollectionUtils.isEmpty(preSetData)) {
                for (Object strObj : preSetData) {
                    String str = strObj.toString();
                    List<String> list = Arrays.asList(str.replace("\"[", "").replace("]\"", "").replace("[", "").replace("]", "").replace("\"", "").split(","));
                    sourceTypes1.add(sourceTypeService.getById(list.get(list.size() - 1)));
                }

            }
        }
        for (CsSystemSourceType csSystemSourceType : sourceTypes1) {
            Map<String, Object> countType = new HashMap<>();
            if (csSystemAdmin != null)
                countType = refugeMapper.statisticRefugTypeCountStatus(csSystemAdmin.getOrgId(), csSystemSourceType.getId());
            Map<String, Object> map = new HashMap<>();
            map.put("refuge_type", csSystemSourceType.getName());
            map.put("refuge_type_code", csSystemSourceType.getId());

            if (null == countType || countType.isEmpty()) {
                map.put("done", 0);
                map.put("allNum", 0);
                map.put("undone", 0);
                countTypeList.add(map);
            } else {
                map.put("done", countType.get("done") == null ? 0 : countType.get("done"));
                map.put("allNum", countType.get("allNum") == null ? 0 : countType.get("allNum"));
                map.put("undone", countType.get("undone") == null ? 0 : countType.get("undone"));
                countTypeList.add(map);
            }
        }

        retMap.put("refugeTypeCount", refugeTypeCount);
        retMap.put("refugeCount", refugeCount);
        retMap.put("countTypeList", countTypeList);
        retMap.put("list", List);
        return retMap;
    }

    public Boolean deleteByDepId(String depId) {
        QueryWrapper<RefugeInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        RefugeInfo refugeInfo = refugeMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(refugeInfo)) {
            int num = refugeMapper.deleteByDepId(refugeInfo.getDepId());
            if (num > 0) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public void snycZwwxByHeadPhone() {
        String ssoAccessToken = zwwxUtils.getGovWxToken();
        QueryWrapper<RefugeInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("head_phone");
        queryWrapper.ne("snyc_state", "0");
        List<RefugeInfo> refugeInfoListFirst = refugeMapper.selectList(queryWrapper);
        for (RefugeInfo refugeInfo : refugeInfoListFirst) {
            Integer code = zwwxUtils.getZWUserInfo(refugeInfo.getHeadPhone(), "refuge-detail/index?depId=" + refugeInfo.getDepId(), ssoAccessToken);
            refugeInfo.setSnycState(code.toString());
            this.saveOrUpdate(refugeInfo);
        }
        queryWrapper.clear();
        queryWrapper.isNotNull("dep_head_phone");
        queryWrapper.ne("dep_snyc_state", "0");
        List<RefugeInfo> refugeInfoListDep = refugeMapper.selectList(queryWrapper);
        for (RefugeInfo refugeInfo : refugeInfoListDep) {
            Integer code = zwwxUtils.getZWUserInfo(refugeInfo.getDepHeadPhone(), "refuge-detail/index?depId=" + refugeInfo.getDepId(), ssoAccessToken);
            refugeInfo.setDepSnycState(code.toString());
            this.saveOrUpdate(refugeInfo);
        }
        queryWrapper.clear();
        queryWrapper.isNotNull("org_head_phone");
        queryWrapper.ne("org_snyc_state", "0");
        List<RefugeInfo> refugeInfoListOrg = refugeMapper.selectList(queryWrapper);
        for (RefugeInfo refugeInfo : refugeInfoListOrg) {
            Integer code = zwwxUtils.getZWUserInfo(refugeInfo.getOrgHeadPhone(), "refuge-detail/index?depId=" + refugeInfo.getDepId(), ssoAccessToken);
            refugeInfo.setOrgSnycState(code.toString());
            this.saveOrUpdate(refugeInfo);
        }
    }
}
